<?php
/**
 * UserData library
 *
 * Contains code needed to save and load a state.
 * @package Packages
 */

/**
 *
 */
require_once(AD_SERVER_PATH . '/pkgs/crypter.php');
require_once(AD_SERVER_PATH . '/pkgs/utils.php');


class CUserData
{
	/**
	 * Execute commands
	 *
	 * Library driver that executes user choice.
	 */
	public function execute()
	{
		ini_set('auto_detect_line_endings', true);
		$sub_cmd = strtolower(CUtils::get_param('sub_cmd'));
		switch ($sub_cmd)
		{
			case 'save':
				CUserData::save_data();
				CLogger::log('INFO', CCrypter::decrypt($_COOKIE['AD_RETS_U']), 'User saved data.');
				break;

			case 'load':
				CUserData::load_data();
				CLogger::log('INFO', CCrypter::decrypt($_COOKIE['AD_RETS_U']), 'User loaded a data.');
				break;

			default:
				break;
		}
	}
	private  function get_user_file_name()
	{
		$_user = CUtils::get_cookie('AD_RETS_U');
		$file_name =  AD_USER_DATA_FOLDER.'data_'.$_user.'.txt';
		if (!is_file($file_name))
		{
			CUtils::write_file($file_name, '', 'w');
		}

		return $file_name;

	}
	/**
	 * Save data
	 * Gets the user's file..
	 * Gets the post data.
	 * FIFO the array with the 100 lines.
	 * Save the file. (TODO change this to save JSON or XML.
	 * Send ok/fail.
	 *
	 */
	private function save_data()
	{

		CLogger::log('INFO', CCrypter::decrypt($_COOKIE['AD_RETS_U']), ('Saving data for ' .  $_user));

		$file_name =  $this->get_user_file_name();

		$frm_vars = CUtils::get_param('frm_vars');
		$comps = CUtils::get_param('comps');
		if(null == $comps)
		{
			$comps = ' ';
		}else
		{
			$comps = str_replace(',', '@', $comps);
		}

		$rec_id = date('Y_m_d_H_i_s');
		$lines = array($rec_id, $rec_id, $comps, $frm_vars );
		
		$result = CUtils::write_csv($file_name, $lines, 'a');


		CUtils::response_start_xml();
		$xml = '<results><success>' . $result . '</success></results>';
		echo($xml);

	}
	function clean_string($s)
	{
		$s = str_replace('@', ',', $s);
		$s = str_replace('[', '', $s);
		$s = str_replace(']', '', $s);
		$s = str_replace('"', '', $s);
		return $s;
	}

	function xmlize_comps($s)
	{
		$comps = $this->clean_string($s);

		return $comps;
	}
	function xmlize_frm_vars($frm_vars)
	{
		$frm_vars = $this->clean_string($frm_vars);
	
		$rows = explode(',', $frm_vars);
		$frm_vars = "";

		foreach ($rows as $row)
		{
			$cell = explode('=', $row);
			$frm_vars .= sprintf("<%s>%s</%s>", $cell[0], $cell[1], $cell[0]);
		}
		return $frm_vars;
	}
	/**
	 * Load data
	 *
	 * Reads the file and sends an xml of it.
	 */
	private function load_data()
	{
		$file_name =  $this->get_user_file_name();

		$fp = fopen($file_name, 'r');
		if($fp)
		{
			$line = fgets($fp);
			CUtils::response_start_xml();
			$xml = '<results><success>true</success><rows>';

			echo ($xml);
			while($line)
			{
				$ar = explode(',', $line);
				$comps = $this->xmlize_comps($ar[2]);
				
				$raw_frm_vars =  $this->clean_string($ar[3]);				
				$frm_vars = $this->xmlize_frm_vars($ar[3]);
				
				$x = sprintf("<row><rec_id>%s</rec_id><created_date>%s</created_date><frm_vars>%s</frm_vars><comps>%s</comps><raw_frm_vars>%s</raw_frm_vars></row>", $ar[0], $this->clean_string($ar[1]), $frm_vars, $comps, $raw_frm_vars);
				echo($x);
				$line = fgets($fp);
			}

			echo('</rows></results>');
			fclose($fp);
		}else
		{
			CUtils::response_start_xml();
			$xml = '<results><success>false</success>';
		}
	}
}
